package com.cxrj.zhsq.handler;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.cxrj.zhsq.Exception.MyException;

/**
 * @Author: WangBo
 * @Description: 自定义异常处理
 * @Date: Create in 15:42 2017/12/15
 * @Modified By:
 */
public class CustomerExceptionHandler implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        ModelAndView mv = new ModelAndView();
        /*  使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常   */
        FastJsonJsonView view = new FastJsonJsonView();
        Map<String, Object> resultMap = new HashMap<>();

        if(ex instanceof MyException) {
            resultMap.put("result",((MyException) ex).getCode());
            resultMap.put("msg",ex.getMessage());
        } else {
            resultMap.put("result",-1);
            resultMap.put("msg","系统繁忙，请稍后再试！");
        }

        view.setAttributesMap(resultMap);
        mv.setView(view);
        return mv;
    }
}
